/**
 * 浏览器类型信息接口声明
 */
export interface browserTypeInterface{
  /** 操作系统 */
  os:string;
  /** 厂商 */
  brand:string;
  /** 版本 */
  version:string;
  /** 平台 */
  platform:string;
  /** 是否运行于安卓 */
  isAndroid:boolean;
  /** 是否运行于iphone */
  isIphone:boolean;
  /** 是否运行于ipad */
  isIpad:boolean;
  /** 是否运行于ipod */
  isIpod:boolean;
  /** 是否运行于Mac */
  isMac:boolean;
  /** 是否运行于Windows */
  isWindows:boolean;
  /** 是否运行于Linux */
  isLinux:boolean;
  /** 是否运行于微信 */
  isWeiXin:boolean;
  /** 是否运行于QQ */
  isQQ:boolean;
}

/**
 * 根据UA获取浏览器类型信息
 * @param {string} ua 浏览器UserAgent信息
 * @returns {browserTypeInterface}
 * ```
 * {
 *  os:string;
 *  brand:string;
 *  version:string;
 *  platform:string;
 *  isAndroid:boolean;
 *  isIphone:boolean;
 *  isIpad:boolean;
 *  isIpod:boolean;
 *  isMac:boolean;
 *  isWindows:boolean;
 *  isLinux:boolean;
 *  isWeiXin:boolean;
 *  isQQ:boolean;
 * }
 * ```
 */
export function getBrowserType (ua:string):browserTypeInterface {
  const unknown = 'unknown';
  const osMatch = ua.match(/(android|macintosh|windows|ipad|iphone|ipod)/i) || [];
  const os = osMatch.length === 2 ? osMatch[1].toLowerCase() : 'linux';
  const platformMatch = ua.match(/(micromessenger)/i) || [];
  let [, platform = unknown] = platformMatch;
  let version;
  let brand;
  if (os === 'android') {
    const versionMatch = ua.match(/(android\s+((\d+\.?)+))/i) || [];
    version = versionMatch[2] || unknown;
  } else if (os === 'iphone' || os === 'ipad') {
    const versionMatch = ua.match(/(os\s+((\d+_?)+))/i) || [];
    version = versionMatch[2] || unknown;
  } else if (os === 'ipod') {
    const versionMatch = ua.match(/[^; ]+(?=;)/g) || [];
    version = versionMatch[2] || unknown;
  } else if (os === 'macintosh') {
    const versionMatch = ua.match(/(mac\s+os\s+x\s+((\d+_?)+))/i) || [];
    version = versionMatch[2] || unknown;
  } else if (os === 'windows') {
    const versionMatch = ua.match(/(windows\s+nt\s+((\d+\.?)+))/i) || [];
    version = versionMatch[2] || unknown;
  } else {
    version = unknown;
  }

  if (brand === undefined) {
    brand = unknown;
  }
  version = version.replace(/_/g, '.');
  platform = platform.toLowerCase();
  return {
    os,
    brand,
    version,
    platform,
    isAndroid: os === 'android',
    isIphone: os === 'iphone',
    isIpad: os === 'ipad',
    isIpod: os === 'ipod',
    isLinux: os === 'linux',
    isMac: os === 'macintosh',
    isWindows: os === 'windows',
    isWeiXin: platform === 'micromessenger',
    isQQ: /qq|QQ\/\d+/i.test(ua)
  };
}